package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangtai.Neusoft.service.NeusoftEmployeeChangeService;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.constVo.ContractConst;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.*;
//import com.zhangtai.modules.dao.ssqlDao.SsqlSalaryGoupDao;
import com.zhangtai.modules.dto.DimissionInfoDto;
import com.zhangtai.modules.dto.DimissionUpcomingDto;
import com.zhangtai.modules.dto.LztkDto;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.employee.*;
import com.zhangtai.modules.entity.regular.RegularBpmEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.common.ImgUrlService;
import com.zhangtai.modules.service.dimission.*;
import com.zhangtai.modules.service.employee.EmployeeRecruitmentService;
import com.zhangtai.modules.vo.*;
import com.zhangtai.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;

//import com.zhangtai.modules.entity.DimissionAndEmployeeInfoEntity;

@RestController
@Api(tags="离职接口")
@RequestMapping("dimission")
@Slf4j
public class DimissionController {

    @Autowired
    private BaseMssqlServiceImpl commonService;

    @Autowired
    private DimissionInfoDao dimissionInfoDao;
    @Autowired
    private DimissionInfoService dimissionInfoService;
    @Autowired
    private ImgUrlDao imgUrlDao;
    @Autowired
    private LoginController loginController;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private DimissionSettlementService dimissionSettlementService;
    @Autowired
    private DimissionAuditService dimissionAuditService;
    @Autowired
    private DimissionUpcomingService dimissionUpcomingService;
    @Autowired
    private ImgUrlService imgUrlService;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;
    @Autowired
    private ContractController contractController;
    @Autowired
    private DimissionSettlementDao dimissionSettlementDao;
    @Autowired
    private DimissionUpcomingDao dimissionUpcomingDao;
    @Autowired
    private NeusoftEmployeeChangeService neusoftEmployeeChangeService;
    @Autowired
    private JobController jobController;
    @Autowired
    private RegularBpmDao regularBpmDao;
//    @Autowired
//    private SsqlSalaryGoupDao ssqlSalaryGoupDao;

    @Autowired
    private  EmployeeRecruitmentService employeeRecruitmentService;


    @GetMapping("/queryDimissionInfoList")
    @ApiOperation(value = "分页查询离职列表")
    @PreAuthorize("hasAuthority('emp:lzsq:get')")
    public R<PageResult<DimissionInfoDto>> queryDimissionInfoList( @RequestParam(value = "oid", required = false) String oid,
                                                                   @RequestParam(value = "name", required = false) String name,
                                                                  @RequestParam(value = "code", required = false) String code,
                                                                  @RequestParam(value = "hiredateStart", required = false) String hiredateStart,
                                                                  @RequestParam(value = "hiredateEnd", required = false) String hiredateEnd,
                                                                   @RequestParam(value = "rurnoverStatus", required = false) Integer rurnoverStatus,
                                                                  @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                  @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                                  HttpServletRequest request)throws Exception{
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();

        Page<DimissionInfoDto> page = new Page<DimissionInfoDto>(pageNum,pageSize);
        List<DimissionInfoDto> recordList = dimissionInfoDao.getDimissionInfoPage(orgIds,oid,name,code,StringUtils.isEmpty(hiredateStart)?null:hiredateStart,StringUtils.isEmpty(hiredateEnd)?null:hiredateEnd,rurnoverStatus,page);
        for (DimissionInfoDto dimissionInfoDto:recordList){
            if (dimissionInfoDto.getJobId() != null && StringUtils.isEmpty(dimissionInfoDto.getJobname()))
                dimissionInfoDto.setJobname(jobController.getJobName(dimissionInfoDto.getJobId()));
            if (dimissionInfoDto.getOrgId() != null && StringUtils.isEmpty(dimissionInfoDto.getOrgname()))
                dimissionInfoDto.setOrgname(jobController.getOrgNameById(dimissionInfoDto.getOrgId()));
            if (dimissionInfoDto.getUnitId() != null && StringUtils.isEmpty(dimissionInfoDto.getUnitname()))
                dimissionInfoDto.setUnitname(jobController.getOrgNameById(dimissionInfoDto.getUnitId()));
        }
        page.setRecords(recordList);
        return  R.ok(new PageResult<DimissionInfoDto>(page));
    }

    @GetMapping("/queryDimissionSettlementList")
    @ApiOperation(value = "新分页查询离职结算列表")
    @PreAuthorize("hasAuthority('emp:lzsq:get')")
    public R<PageResult<DimissionInfoDto>> queryDimissionSettlementList(
                                                                        @RequestParam(value = "name", required = false) String name,
                                                                        @RequestParam(value = "code", required = false) String code,
                                                                        @RequestParam(value = "hiredateStart", required = false) String hiredateStart,
                                                                        @RequestParam(value = "hiredateEnd", required = false) String hiredateEnd,
                                                                        @RequestParam(value = "status",  required = false) Integer status, //审批状态
                                                                        @RequestParam(value = "processingStatus",required = false) Integer processingStatus, //处理状态
                                                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                                  HttpServletRequest request)throws Exception{
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        Page page = new Page(pageNum,pageSize);
        List<DimissionInfoDto>  recordList  = dimissionSettlementDao.getDimissionInfoList(orgIds,null,
                name,
                code,
                StringUtils.isEmpty(hiredateStart)?null:hiredateStart,
                StringUtils.isEmpty(hiredateEnd)?null:hiredateEnd,
                status,processingStatus,page);
        for(DimissionInfoDto dimissionInfoDto:recordList){
            List<String> annexUrl=new ArrayList<>();
            if(!StringUtils.isEmpty(dimissionInfoDto.getAnnexUrl())){
                String[] UrlList=dimissionInfoDto.getAnnexUrl().split(",");
                annexUrl= Arrays.asList(UrlList);
            }
            dimissionInfoDto.setFileUrlList(annexUrl);
        }
        for (DimissionInfoDto dimissionInfoDto:recordList){
            if (dimissionInfoDto.getJobId() != null && StringUtils.isEmpty(dimissionInfoDto.getJobname()))
                dimissionInfoDto.setJobname(jobController.getJobName(dimissionInfoDto.getJobId()));
            if (dimissionInfoDto.getOrgId() != null && StringUtils.isEmpty(dimissionInfoDto.getOrgname()))
                dimissionInfoDto.setOrgname(jobController.getOrgNameById(dimissionInfoDto.getOrgId()));
            if (dimissionInfoDto.getUnitId() != null && StringUtils.isEmpty(dimissionInfoDto.getUnitname()))
                dimissionInfoDto.setUnitname(jobController.getOrgNameById(dimissionInfoDto.getUnitId()));
        }
        page.setRecords(recordList);
        return  R.ok(new PageResult<DimissionInfoDto>(page));
    }

//    @GetMapping("/getDimissionInfoList")
//    @ApiOperation(value = "查询离职申请已审批列表数据")
//    @PreAuthorize("hasAuthority('emp:dimission:get')")
//    public R<PageResult<DimissionInfoDto>> getDimissionSettlementList(@RequestParam(value = "status",  defaultValue = "2") Integer status, //审批状态
//                                                                        HttpServletRequest request)throws Exception{
//        List<DimissionInfoEntity>  dimissionInfoEntityList  = dimissionInfoDao.selectList(new QueryWrapper<DimissionInfoEntity>()
//                .eq("is_delete", 0).eq("rurnover_status", status));
//        return  R.ok(dimissionInfoEntityList);
//    }


    @GetMapping("/queryDimissionAuditList")
    @ApiOperation(value = "新分页查询离职审计通知列表")
    @PreAuthorize("hasAuthority('emp:lzsq:get')")
    public R queryDimissionAuditList(@RequestParam(value = "name", required = false) String name,
                                                                        @RequestParam(value = "code", required = false) String code,
                                                                        @RequestParam(value = "hiredateStart", required = false) String hiredateStart,
                                                                        @RequestParam(value = "hiredateEnd", required = false) String hiredateEnd,
                                                                   @RequestParam(value = "jobLevelId", required = false) Long jobLevelId, //职级id
                                                                        @RequestParam(value = "lineId", required = false) Long lineId, //专业职级id
                                                                        @RequestParam(value = "jobSystemId", required = false) Long jobSystemId, //专业职级id
                                                                        @RequestParam(value = "status", required = false) Integer status, //审批状态
                                                                         @RequestParam(value = "upcomingStatus", required = false) Integer upcomingStatus, //审计待办状态
                                                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                        @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                                        HttpServletRequest request)throws Exception{

        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();

        PageResult pageResult=  dimissionAuditService.getDimissionAuditPageList(
                orgIds,
                name,
                code,
                StringUtils.isEmpty(hiredateStart)?null:hiredateStart,
                StringUtils.isEmpty(hiredateEnd)?null:hiredateEnd,
                jobLevelId,
                lineId,
                jobSystemId,status,upcomingStatus,pageNum,pageSize);
        return  R.ok(pageResult);
    }

    @GetMapping("/queryDimissionUpcomingtList")
    @ApiOperation(value = "分页查询离任审计待办列表")
    @PreAuthorize("hasAuthority('emp:lzsq:get')")
    public R<PageResult<DimissionUpcomingDto>> queryDimissionUpcomingtList(@RequestParam(value = "name", required = false) String name,
                                                                           @RequestParam(value = "code", required = false) String code,
                                                                           @RequestParam(value = "hiredateStart", required = false) String hiredateStart,
                                                                           @RequestParam(value = "hiredateEnd", required = false) String hiredateEnd,
                                                                           @RequestParam(value = "jobLevelId", required = false) Long jobLevelId, //职级id
                                                                           @RequestParam(value = "lineId", required = false) Long lineId, //专业职级id
                                                                           @RequestParam(value = "jobSystemId", required = false) Long jobSystemId, //专业职级id
                                                                           @RequestParam(value = "status",  required = false) Integer status, //审批状态
                                                                           @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                           @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                                           HttpServletRequest request)throws Exception{
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        Page page = new Page(pageNum,pageSize);
        List<DimissionUpcomingDto>  recordList  =  dimissionUpcomingDao.getDimissionUpcomingList(
                orgIds,
                org.apache.commons.lang3.StringUtils.isEmpty(name)?null:name,
                org.apache.commons.lang3.StringUtils.isEmpty(code)?null:code,
                StringUtils.isEmpty(hiredateStart)?null:hiredateStart,
                StringUtils.isEmpty(hiredateEnd)?null:hiredateEnd,
                jobLevelId,
                lineId,
                jobSystemId,status,page);
            for (DimissionUpcomingDto dimissionUpcomingDto:recordList){
//       // 封装附件
               List<String> annexUrl=new ArrayList<>();
                if(!StringUtils.isEmpty(dimissionUpcomingDto.getAnnexUrl())){
                    String[] UrlList=dimissionUpcomingDto.getAnnexUrl().split(",");
                    annexUrl= Arrays.asList(UrlList);
                }
                dimissionUpcomingDto.setAnnexUrlList(annexUrl);
                }

        page.setRecords(recordList);
        return  R.ok(new PageResult<DimissionUpcomingDto>(page));
    }

    @PostMapping("/saveDimissionInfo")
    @ApiOperation(value="添加员工离职信息")
    @SysAuthorityLog(value = "添加员工离职信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:lzsq:update')")
    public R saveDimissionInfo(@RequestBody @Valid DimissionInfoVo dimissionInfoVo, HttpServletRequest request) throws Exception {

        JSONObject data =loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return  R.error("请先登录");
        }

        DimissionInfoEntity dimissionInfoEntity=BeanUtilsMabach.doToDto(dimissionInfoVo,DimissionInfoEntity.class);

        long id = snowflakeIdWorker.nextId();
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("oid",dimissionInfoVo.getOid()));
       String processNumber= getDimissionInfoNum();
        dimissionInfoEntity.setApplyDepartment(data.getString("department"));
        ArrayList<String> fileUrlList=dimissionInfoVo.getUrlIdsList();
        if(!CollectionUtils.isEmpty(fileUrlList)) {
            saveFile(dimissionInfoEntity.getOid(), fileUrlList, "离职附件",8);
        }
        dimissionInfoEntity.setUrlIds(CollectionUtils.isEmpty(fileUrlList)?"":ListToString(fileUrlList));
        R r;
        if(dimissionInfoEntity.getId()==null) {
            dimissionInfoEntity.setId(id);
            dimissionInfoEntity.setIsDelete(0);
            dimissionInfoEntity.setCreateTime(new Date());
            dimissionInfoEntity.setRurnoverStatus(0);
            dimissionInfoEntity.setIsRemind(0);
            dimissionInfoEntity.setSptype(7);
            dimissionInfoEntity.setUnitId(employeeInfoEntity.getUnitId());
            dimissionInfoEntity.setProcessNumber(processNumber);
            r=  dimissionInfoService.saveE(dimissionInfoEntity);
        }else {
           r= dimissionInfoService.updateByIdE(dimissionInfoEntity);
        }
        return r;
    }

    @DeleteMapping("/deleteDimissionInfo")
    @ApiOperation(value = "删除员工离职信息")
    @Transactional
    public R deleteDimissionInfo(@RequestParam(value = "id" ) String id){
        DimissionInfoEntity dimissionInfoEntity = dimissionInfoDao.selectOne(new QueryWrapper<DimissionInfoEntity>().eq("id",id).eq("is_delete", 0));
        if(!org.springframework.util.ObjectUtils.isEmpty(dimissionInfoEntity)) {
            dimissionInfoEntity.setIsDelete(1);
            dimissionInfoDao.updateById(dimissionInfoEntity);
        }
        return R.ok();
    }

    @DeleteMapping("/deleteDimissionSettlement")
    @ApiOperation(value = "删除员工离职结算信息")
    @Transactional
    public R deleteDimissionSettlement(@RequestParam(value = "id" ) String id){
        DimissionSettlementEntity dimissionSettlementEntity = dimissionSettlementDao.selectOne(new QueryWrapper<DimissionSettlementEntity>().eq("id",id).eq("is_delete", 0));
        if(!org.springframework.util.ObjectUtils.isEmpty(dimissionSettlementEntity)) {
            dimissionSettlementEntity.setIsDelete(1);
            dimissionSettlementDao.updateById(dimissionSettlementEntity);
        }
        return R.ok();
    }


    @PostMapping("/updateDimissionSettlement")
    @ApiOperation(value="修改员工离职结算信息")
    @SysAuthorityLog(value = "修改员工离职结算信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:lzsq:update')")
    public R updateDimissionSettlement(@RequestBody @Valid DimissionSettlemntVo dimissionSettlemntVo,HttpServletRequest request) throws Exception {
        JSONObject data =loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return  R.error("请先登录");
        }
        DimissionSettlementEntity dimissionSettlementEntity=BeanUtilsMabach.doToDto(dimissionSettlemntVo,DimissionSettlementEntity.class);
        dimissionSettlementEntity.setApplyTime(new Date());

        DimissionInfoEntity dimissionInfoEntity= dimissionInfoService.getByIdE(dimissionSettlementEntity.getDimissionId());
        ArrayList<String> fileUrlList=dimissionSettlemntVo.getUrlIdsList();
        if(!CollectionUtils.isEmpty(fileUrlList)) {
            saveFile(dimissionInfoEntity.getOid(), fileUrlList, "离职结算附件",8);
        }
        dimissionSettlementEntity.setAnnexUrl(CollectionUtils.isEmpty(fileUrlList)?"":ListToString(fileUrlList));
       return dimissionSettlementService.updateByIdE(dimissionSettlementEntity);
    }

    @PostMapping("/updateDimissionSettlementStatus")
    @ApiOperation(value = "修改离职结算处理状态")
    @SysAuthorityLog(value = "修改离职结算处理状态")
//    @Transactional
    public R updateDimissionSettlementStatus(@RequestParam(value = "id") String id,
                                             @RequestParam(value = "processingStatus") Integer processingStatus,
                                             @RequestParam(value = "dimissionTime",required = false) String dimissionTime,
                                             @RequestParam(value = "reason",required = false) String reason){
        DimissionSettlementEntity dimissionSettlementEntity= dimissionSettlementService.getByIdE(Long.valueOf(id));
        DimissionInfoEntity dimissionInfoEntity=dimissionInfoService.getByIdE(dimissionSettlementEntity.getDimissionId());
        if(dimissionTime!=null){
            dimissionInfoEntity.setDimissionTime(DateUtils.parseDateYMD(dimissionTime));
        }

        // 往明源系统返写 Preparing: INSERT INTO [dotnet_erp60]
        //  结算发起申请 传明源的字段
//        List<LztkDto> mygts = ssqlSalaryGoupDao.getMygt(dimissionInfoEntity.getApplyCode());
//
//        Date qiem = new Date();
//        for (LztkDto  lztk: mygts) {
//            ssqlSalaryGoupDao.insertMygt(lztk.getBUGUID(),lztk.getFaPackGUID(),lztk.getFaGtPackGUID(),lztk.getUserGUID(),lztk.getFaPackName(),lztk.getUserName(),lztk.getWorkNo()
//                    ,lztk.getInvestyear(),lztk.getPayAmount(),lztk.getPayPrincipal(),lztk.getReturnPrincipal(),lztk.getBackOverPrincipal(),lztk.getFactReturnAmount(),lztk.getFactPrincipal(),lztk.getSyje(),
//                    qiem,0);
//        }

        dimissionInfoService.updateByIdE(dimissionInfoEntity);
        EmployeeInfoEntity employeeInfoEntity= employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("oid",dimissionInfoEntity.getOid())
                .eq("is_delete", 0));
        //如果离职结算通过，则把转正状态修改为 3 ：离职终止
        if(!ObjectUtils.isEmpty(employeeInfoEntity)) {
            Integer apply = 0;
            Integer postpone = 2;
            Integer oldEmployee = 2;
            //待转正、延期转正状态下的新员工置为离职终止
            if((apply.equals(employeeInfoEntity.getIsRegular())||postpone.equals(employeeInfoEntity.getIsRegular()))&&!oldEmployee.equals(employeeInfoEntity.getIsReinstate())){
                employeeInfoEntity.setIsRegular(5); //离职终止
            }
            employeeInfoEntity.setRegularBpmStatus(2);  //审批通过
            employeeInfoEntity.setIsRegularRemind(1);
            employeeInfoEntity.setDimissionTime(dimissionInfoEntity.getDimissionTime());
            employeeInfoEntity.setEmployeestatus("3");
            employeeInfoDao.updateById(employeeInfoEntity);

            //修改招聘数据
            if(!org.springframework.util.StringUtils.isEmpty(employeeInfoEntity.getRecruitmentId())){
                EmployeeRecruitmentEntity employeeRecruitmentEntity=new EmployeeRecruitmentEntity();
                employeeRecruitmentEntity.setId(employeeInfoEntity.getRecruitmentId());
                employeeRecruitmentEntity.setIsRegular(5); //离职终止
                employeeRecruitmentEntity.setRegularBpmStatus(2);  //审批通过
                employeeRecruitmentEntity.setIsRegularRemind(1);
                employeeRecruitmentEntity.setEmployeestatus("3");
                employeeRecruitmentService.updateByIdE(employeeRecruitmentEntity);
            }

        }
        //查找当前员工是否有管理待转正的数据，有的话更新为离职终止
        List<Integer> status = new ArrayList<>();
        status.add(0);
        status.add(2);
        List<RegularBpmEntity> regularBpmEntity = regularBpmDao.selectList(new QueryWrapper<RegularBpmEntity>().in("is_regular",status).eq("oid",dimissionInfoEntity.getOid()).eq("is_delete",0));
        if(!CollectionUtils.isEmpty(regularBpmEntity)){
            for(RegularBpmEntity entity:regularBpmEntity){
                entity.setIsRegular(3);
                entity.setRegularBpmStatus(3);
                entity.setIsRegularRemind(1);
                regularBpmDao.updateById(entity);
            }
        }
        dimissionSettlementEntity.setProcessingStatus(processingStatus);
        dimissionSettlementEntity.setReason(reason);
        //新建一条解除合同
        ContractNewVo vo = new ContractNewVo();
        vo.setOid(employeeInfoEntity.getOid());
        vo.setOperateType(ContractConst.CONTRACT_OPERATE_DIMISSION);
        vo.setType(ContractConst.CONTRACT_TYPE_TERMINATE);
        vo.setContractType(ContractConst.CONTRACT_MANAGER_TERMINATE);
        vo.setContractBeginDate(dimissionInfoEntity.getDimissionTime());
        vo.setRelateId(dimissionSettlementEntity.getId());
        contractController.saveNewContract(vo);

        dimissionSettlementService.updateByIdE(dimissionSettlementEntity);
        //离职结算时调用异动接口
        neusoftEmployeeChangeService.uploadDismissChange(dimissionInfoEntity);
       return R.ok();
    }


    @PostMapping("/saveDimissionAudit")
    @ApiOperation(value="添加员工离职审计通知信息")
    @SysAuthorityLog(value = "添加员工离职审计通知信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:lzsq:update')")
    public R saveDimissionAudit(@RequestBody @Valid DimissionAuditVo dimissionAuditVo, HttpServletRequest request) throws Exception {

        JSONObject data =loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)) {
            return  R.error("请先登录");
        }
        DimissionAuditEntity dimissionAuditEntity=BeanUtilsMabach.doToDto(dimissionAuditVo,DimissionAuditEntity.class);
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("oid",dimissionAuditVo.getOid()));
        long id = snowflakeIdWorker.nextId();
        dimissionAuditEntity.setId(id);
        dimissionAuditEntity.setCreateTime(new Date());
        dimissionAuditEntity.setStatus(0);
        dimissionAuditEntity.setUpcomingStatus(0);
        dimissionAuditEntity.setIsDelete(0);
        dimissionAuditEntity.setSptype(9);
        dimissionAuditEntity.setUnitId(employeeInfoEntity.getUnitId());
        dimissionAuditEntity.setInsetDate(new Date());
        List<DimissionInfoEntity> dimissionInfoEntityList=dimissionInfoDao.selectList(new QueryWrapper<DimissionInfoEntity>()
                .eq("is_delete", 0).eq("rurnover_status", 2).eq("oid", dimissionAuditVo.getOid()).orderByDesc("create_time"));
        if(!CollectionUtils.isEmpty(dimissionInfoEntityList)){
            dimissionAuditEntity.setDimissionTime(dimissionInfoEntityList.get(0).getDimissionTime());
        }

        ArrayList<String> fileUrlList=dimissionAuditVo.getUrlIdsList();
        if(!CollectionUtils.isEmpty(fileUrlList)) {
            saveFile(dimissionAuditVo.getOid(), fileUrlList, "离任审计附件",8);
        }
        dimissionAuditEntity.setAnnexUrl(CollectionUtils.isEmpty(fileUrlList)?"":ListToString(fileUrlList));
        return   dimissionAuditService.saveE(dimissionAuditEntity);

    }

    @PostMapping("/updateDimissionAudit")
    @ApiOperation(value="修改员工离职审计通知信息")
    @SysAuthorityLog(value = "修改员工离职审计通知信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:lzsq:update')")
    public R updateDimissionAudit(@RequestBody @Valid DimissionAuditVo dimissionAuditVo, HttpServletRequest request) throws Exception {
        if(dimissionAuditVo.getId()==null){
          return   R.error("离任审计通知id不能为空");
        }
        DimissionAuditEntity dimissionAuditEntity=BeanUtilsMabach.doToDto(dimissionAuditVo,DimissionAuditEntity.class);
        List<DimissionInfoEntity> dimissionInfoEntityList=dimissionInfoDao.selectList(new QueryWrapper<DimissionInfoEntity>()
                .eq("is_delete", 0).eq("rurnover_status", 2).eq("oid", dimissionAuditVo.getOid()).orderByDesc("create_time"));
        if(!CollectionUtils.isEmpty(dimissionInfoEntityList)){
            dimissionAuditEntity.setDimissionTime(dimissionInfoEntityList.get(0).getDimissionTime());
        }
        EmployeeInfoEntity employeeInfoEntity = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("oid",dimissionAuditVo.getOid()));
        dimissionAuditEntity.setUnitId(employeeInfoEntity.getUnitId());
        ArrayList<String> fileUrlList=dimissionAuditVo.getUrlIdsList();
        if(!CollectionUtils.isEmpty(fileUrlList)) {
            saveFile(dimissionAuditVo.getOid(), fileUrlList, "离任审计附件",8);
        }
        dimissionAuditEntity.setAnnexUrl(CollectionUtils.isEmpty(fileUrlList)?"":ListToString(fileUrlList));
        return   dimissionAuditService.updateByIdE(dimissionAuditEntity);

    }

    @PostMapping("/saveDimissionUpcoming")
    @ApiOperation(value="修改员工离职审计待办信息")
    @SysAuthorityLog(value = "修改员工离职审计待办信息")
    @Transactional
    @PreAuthorize("hasAuthority('emp:lzsq:update')")
    public R saveDimissionUpcoming(@RequestBody @Valid DimissionUpcomingVo dimissionUpcomingVo, HttpServletRequest request) throws Exception {
        DimissionUpcomingEntity dimissionUpcomingEntity=BeanUtilsMabach.doToDto(dimissionUpcomingVo,DimissionUpcomingEntity.class);
        DimissionAuditEntity dimissionAuditEntity= dimissionAuditService.getByIdE(dimissionUpcomingEntity.getId());
        ArrayList<String> fileUrlList=dimissionUpcomingVo.getUrlIdsList();
        if(!CollectionUtils.isEmpty(fileUrlList)) {
            saveFile(dimissionAuditEntity.getOid(), fileUrlList, "离任审计附件",8);
        }
        dimissionUpcomingEntity.setAnnexUrl(CollectionUtils.isEmpty(fileUrlList)?"":ListToString(fileUrlList));
       /* if(1==dimissionUpcomingVo.getStatus()){
            EmployeeInfoEntity employeeInfoEntity= employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("oid",dimissionAuditEntity.getOid())
                .eq("is_delete", 0));
            employeeInfoEntity.setDimissionTime(dimissionAuditEntity.getDimissionTime());
            employeeInfoDao.updateById(employeeInfoEntity);
        }*/
        return  dimissionUpcomingService.updateByIdE(dimissionUpcomingEntity);

    }


    @GetMapping("/getEmployessInfoByCode/{code}")
    @ApiOperation(value="根据code 查找员工信息")
    public R<EmployeeInfoEntity> getEmployessInfoByCode(@PathVariable("code") String code) {

        List<EmployeeInfoEntity> employeeInfoEntitys = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().eq("code", code).eq("is_delete", 0).orderByDesc("create_time"));
        if (!CollectionUtils.isEmpty(employeeInfoEntitys)) {
          //  employeeModelDto = BeanUtilsMabach.doToDto(employeeInfoEntitys.get(0), EmployeeModelDto.class);
            return R.ok(employeeInfoEntitys.get(0));
        }
        //        先去查询本地库，如果有则返回最新的那条
//如果本地库没有，则去sqlServer查询
        EmployeeInfoEntity employeeInfoEntity = commonService.finEmpFromMssqlByCode(code);
       // employeeModelDto = findEmpByIdByCode(code);
        if (ObjectUtils.isEmpty(employeeInfoEntity)){
            return R.ok();
        }
        return R.ok(employeeInfoEntity);
    }

    @GetMapping("/getEmployessInfoByCodeList")
    @ApiOperation(value="根据code 数组  查找员工信息")
    public R getEmployessInfoByCodeList(@RequestParam("code") String codes) {

        String[] codeStr=	codes.split(",");
        List<String> list=Arrays.asList(codeStr);
        List<String>  stringList = new ArrayList<>(new HashSet<>(list));
        String notFoundStr="";
        List<EmployeeInfoEntity> employeeInfoEntitys = employeeInfoDao.selectList(new QueryWrapper<EmployeeInfoEntity>().in("code", stringList).eq("is_delete", 0).orderByDesc("create_time"));
        List<EmployeeInfoEntity> employeeInfoEntityList=new ArrayList<>();
        List<String> isCode=new ArrayList<>();
        for (String code:stringList){
            for(EmployeeInfoEntity employeeInfoEntity:employeeInfoEntitys){
                if(code.equals(employeeInfoEntity.getCode())){
                    isCode.add(code);
                    continue;
                }
            }
        }
        stringList.removeAll(isCode);
        for(String code:stringList) {
            //        先去查询本地库，如果有则返回最新的那条
            //如果本地库没有，则去sqlServer查询
            EmployeeInfoEntity  employeeInfoEntity = commonService.finEmpFromMssqlByCode(code);
            // employeeModelDto = findEmpByIdByCode(code);
            if (ObjectUtils.isEmpty(employeeInfoEntity)) {
                notFoundStr+=code+",";
            }else {
                employeeInfoEntityList.add(employeeInfoEntity) ;
            }
        }
        notFoundStr = notFoundStr.isEmpty() ? "根据员工工号全部导入成功！" : "根据员工工号未找到："+notFoundStr;
        employeeInfoEntitys.addAll(employeeInfoEntityList);
        JSONObject object=new JSONObject();
        object.put("notFoundStr",notFoundStr);
        object.put("employeeInfoEntityList",employeeInfoEntitys);
        return R.ok(object);
    }





    //附件保存
    public void saveFile(Long oid, ArrayList<String> fileList,String name,Integer type){
        for (String s : fileList) {
            imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("url", s).eq("type", type));
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setName(name);
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setType(type);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlEntity.setUrl(s);
            imgUrlService.saveE(imgUrlEntity);
        }

    }
    public String ListToString(ArrayList<String> fileUrlList){
        String Url="";
        for ( String s:fileUrlList){
            Url+=s+",";
        }
        return Url.substring(0,Url.length()-1);
    }


    //生成流程编号
    public String getDimissionInfoNum(){
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String datestr = format.format(date);
        String nm = new SimpleDateFormat("yyyyMMdd").format(date);
        Long max = dimissionInfoDao.getDimissionInfoNum(datestr)+1;
        String employeeOidStr = String.format("%05d", max);
        return "ZF" + nm+employeeOidStr;
    }

}
